package www.openteam.com.ui.business.other;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;
import www.openteam.com.R;
import www.openteam.com.base.mBaseFragment;
import www.openteam.com.bean.JiJian;
import www.openteam.com.bean.PDistrubition;
import www.openteam.com.bean.Worker;
import www.openteam.com.contract.business.other.PSearchContract;
import www.openteam.com.presenter.business.other.PSearchPresenter;
import www.openteam.com.tool.ToastUtil;

/**
 * Created by kylin on 2017/5/16.
 */

public class PSearchFragment extends mBaseFragment<PSearchPresenter>
        implements PSearchContract.PSearchView {


    private String TAG = PSearchFragment.class.getSimpleName();
    private FragmentManager manager;
    private FragmentTransaction ft;
    private Worker.DataBeanX.DataBean theWork;
    @Bind(R.id.et_employee)
    EditText et_employee;
    @Bind(R.id.et_ename)
    EditText et_ename;
    @Bind(R.id.et_job)
    EditText et_job;
    @Bind(R.id.btn_ok_add)
    Button btn_ok_add;
    @Bind(R.id.btn_employee)
    Button btn_employee;
    int i = 0;
    public ButtonOkClick buttonOkClick;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);

//        getView(inflater, container);
        view = inflater.inflate(getLayoutId(), container, false);
//        iv_arrow.setOnTouchListener(new OptionMenuTouchListener());
        setHasOptionsMenu(true);
        manager = getFragmentManager();
        mPresenter = loadPresenter();
        initCommonData();
        initView();
        initListener();
        initData();
        ButterKnife.bind(this, view);
        return view;
    }


    private void initCommonData() {
        if (mPresenter != null)
            mPresenter.attachView(this);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        btn_employee.setOnClickListener(this);
        btn_ok_add.setOnClickListener(this);
        et_employee.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                Log.d(TAG, "onKey: wm" + keyCode + ":" + event.getAction());
                if (keyCode == KeyEvent.KEYCODE_BACK
                        && event.getAction() == KeyEvent.ACTION_DOWN) {
                    //关闭软键盘
                    Log.d(TAG, "onKey: jg");
                    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(et_employee.getWindowToken(), 0);
                    //使得根View重新获取焦点，以监听返回键

                    getFocus();
                    return true;
                }
                return false;
            }
        });

    }

    @Override
    protected void initView() {
        ButterKnife.bind(this, view);
        et_employee.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 判断输入不为空，按钮可点击
                if (et_employee.length() != 0) {
                    btn_employee.setEnabled(true);
                    btn_employee.setBackgroundResource(R.drawable.btn_small_green_selector);
                } else {
                    btn_employee.setEnabled(false);
                    btn_employee.setBackgroundResource(R.color.gray);
                    et_job.setText("");
                    et_ename.setText("");
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        et_ename.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if ((et_ename.length() != 0) && (et_employee.length() != 0)) {
                    btn_ok_add.setEnabled(true);
                    btn_ok_add.setBackgroundResource(R.drawable.btn_small_green_selector);
                } else {
                    btn_ok_add.setEnabled(false);
                    btn_ok_add.setBackgroundResource(R.color.gray);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    @Override
    protected void otherViewClick(View view) {

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_ok_add:
                PDistrubition.DataBeanX.DataBean dataEntity = new PDistrubition.DataBeanX.DataBean();
                dataEntity.setCode(theWork.getCode());
                dataEntity.setJob(theWork.getJob());
                dataEntity.setName(theWork.getName());
                buttonOkClick.returnWorker(dataEntity);
                ft = manager.beginTransaction();
                ft.remove(PSearchFragment.this).show(manager.findFragmentByTag("baseWorkOrderFragment"));
                ft.commit();
                break;
            case R.id.btn_employee:
                createProgressDialog("正在查询,请稍等...");
                mPresenter.findWorker(et_employee.getText().toString());
                break;
        }
    }

    @Override
    protected PSearchPresenter loadPresenter() {
        return new PSearchPresenter();
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_peoples;
    }

    @Override
    public void onResume() {
        super.onResume();
        getFocus();
    }

    @Override
    public void onPause() {
        super.onPause();

        getFocus();

    }


    private void getFocus() {
        getView().setFocusable(true);
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();


        getView().setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                Log.d(TAG, "onKey: " + keyCode + ":" + event.getAction() + ":" + ":::::");
                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
                    ft = manager.beginTransaction();
                    ft.remove(PSearchFragment.this).show(manager.findFragmentByTag("workOrderFragment"));
                    ft.commit();
                    return true;// 未处理
                }
//                else if (event.getAction() == 1 && keyCode == KeyEvent.KEYCODE_BACK) {
//                    Log.d(TAG, "onKey: jg");
//                    ft = manager.beginTransaction();
//                    ft.remove(PSearchFragment.this).show(manager.findFragmentByTag("workOrderFragment"));
//                    ft.commit();
//                    return false;// 未处理
//                }
//                return true;


//                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
//            /*
//			 * 注意在if判断中要加一个event.getAction() == KeyEvent.ACTION_DOWN判断，
//			 * 因为按键有两个事件ACTION_DOWN和ACTION_UP，也就是按下和松开，
//			 * 如果不加这个判断，代码会执行两遍
//			 */
//                if (event.getAction() == KeyEvent.ACTION_DOWN) {
//                    Log.d(TAG, "onKey: " + keyCode + "-:" + event.getAction() + ":" + ":::::");
//                    ft = manager.beginTransaction();
//                    ft.remove(PSearchFragment.this).show(manager.findFragmentByTag("workOrderFragment"));
//                    ft.commit();
//                    return true;
//                }
//                return false;

//                if (keyCode == KeyEvent.KEYCODE_BACK
//                        && event.getAction() == KeyEvent.ACTION_UP) {
//                    //关闭软键盘
//                    Log.d(TAG, "onKey: " + keyCode + "----:" + event.getAction() + ":" + ":::::");
//                    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
//                    imm.hideSoftInputFromWindow(et_employee.getWindowToken(), 0);
//                    //使得根View重新获取焦点，以监听返回键
//
//                }
                return false;
            }
        });

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.add(0, 1, 0, "return").setShowAsAction(
                MenuItem.SHOW_AS_ACTION_IF_ROOM);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
//        if (item.getItemId()==android.R.id.home){
//            Log.d(TAG, "onOptionsItemSelected: +home");
//            getActivity().getFragmentManager().popBackStack();
//            return false;
//        }
        switch (item.getItemId()) {
            case 1://这个0是上图中“操作”字样的ItmeId
                ft = manager.beginTransaction();
                ft.remove(PSearchFragment.this).show(manager.findFragmentByTag("workOrderFragment"));
                ft.commit();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }


    @Override
    public void queryPSuccess(Worker worker) {
        mProgressDialog.cancel();

        theWork = worker.getData().getData().get(0);
        et_ename.setText(theWork.getName());
        et_job.setText(theWork.getJob());
    }


    @Override
    public void queryPFail(String failMsg) {
        ToastUtil.showToast(getContext(), failMsg);
        mProgressDialog.cancel();
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public interface ButtonOkClick {

        void returnWorker(PDistrubition.DataBeanX.DataBean dataEntity);

    }

    public void theOkClick(ButtonOkClick buttonOkClick) {
        this.buttonOkClick = buttonOkClick;
    }
}
